'''
“顺意e生”百万医疗保险
'''

import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,json
from common.helper import Helper


class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()

        self.name = "顺意e生百万医疗保险"

    #生成产品数据
    def genProductInfo(self):

        #年龄段
        years = [str(i) for i in range(0,60)]

        #有无社保 0无社保 1有社保
        socialSec = ["0","1"]

        #投保方案 T3 经济型 T2 优选型 T3 尊享版
        programme = ["P122903-T3","P122903-T2","P122903-T1"]

        for v in product( years , socialSec,programme ):

            #写入数据库
            self.mysql.cursor.execute(  domain[self.name]["insert_sql"].format( v[0],v[1],v[2]))

            self.mysql._conn.commit()

            print("数据写入成功",v)


    #执行爬虫
    def requestJson(self,dt=None):


        data = {

            "quoteList": [{
                "insureId": "1",
                "quoteReq": {
                    "productCode": "P122903",
                    "packageCode": dt["programme"],
                    "channelCode": "micro",
                    "discountKey": "",
                    "priceFactor": [{
                        "itemType": "insured",
                        "itemFieldCode": "age",
                        "itemFieldValue": dt["year"]
                    }, {
                        "itemType": "insured_field",
                        "itemFieldCode": "shebao",
                        "itemFieldValue": dt["socialSec"]
                    }]
                }
            }]
        }

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=json.dumps( data ))

        if r.status_code == 200:

            totalPrice = r.json()["data"]["actualPremiumAmt"] / 100

            price = Helper.decimalParse( totalPrice )
            data = {

                "name":self.name,

                "id":dt["id"],

                "price":price

            }

            self.mysql.updatePrice( data )


        else:

            data = {

                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.randTask( data )

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":1
            }
            self.mysql.updateTask( data )

            self.requestJson( dt )


if __name__ == '__main__':

    s = Spider()
    s.main()
